package com.example.zzmftp.util;

import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.example.zzmftp.config.FtpProperties;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Ftp 工具类
 */
public class FtpHelper {

    private FTPClient ftp;


    public FtpHelper() {
    }
    /**
     * 初始化Ftp信息     *     * @param ftpServer   ftp服务器地址     * @param ftpPort     Ftp端口号     * @param ftpUsername ftp 用户名     * @param ftpPassword ftp 密码
     */
    public FtpHelper(FtpProperties ftpProperties) {
        connect(ftpProperties.getIp(), 21, ftpProperties.getUserName(), ftpProperties.getPasswd());
    }

    /**
     * 连接到ftp     *     * @param ftpServer   ftp服务器地址     * @param ftpPort     Ftp端口号     * @param ftpUsername ftp 用户名     * @param ftpPassword ftp 密码
     */
    public void connect(String ftpServer, int ftpPort, String ftpUsername, String ftpPassword) {
        ftp = new FTPClient();
        try {
            ftp.setControlEncoding("UTF-8");
            ftp.setRemoteHost(ftpServer);
            ftp.setRemotePort(ftpPort);
            ftp.setTimeout(6000);
            ftp.setConnectMode(FTPConnectMode.ACTIVE);
            ftp.connect();
            ftp.login(ftpUsername, ftpPassword);
            ftp.setType(FTPTransferType.BINARY);
        } catch (Exception e) {
            e.printStackTrace();
            ftp = null;
        }
    }

    /**
     * 更改ftp路径     *     * @param ftp     * @param dirName     * @return
     */
    public boolean checkDirectory(FTPClient ftp, String dirName) {
        boolean flag;
        try {
            ftp.chdir(dirName);
            flag = true;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 断开ftp链接
     */
    public void disconnect() {
        try {
            if (ftp.connected()) {
                ftp.quit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取ftp文件流     *     * @param filePath ftp文件路径     * @return s     * @throws Exception
     */
    public InputStream downloadFile(String filePath) throws Exception {
        InputStream inputStream = null;
        String fileName = "";
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);
            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                ftp.chdir(s);
            }
        }
        byte[] data;
        try {
            data = ftp.get(fileName);
            inputStream = new ByteArrayInputStream(data);
            disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }
    /**
     * 上传文件到ftp     *     * @param inStream 上传的文件流     * @param filePath 上传路径     * @throws Exception
     */
    public String uploadFile(InputStream inStream, String fileName,String pathUrl) throws Exception {
        String timePath = getTimePath();
        String filePath = pathUrl + timePath + fileName;
        if (inStream == null) {
            return null;
        }
        int len = filePath.lastIndexOf("/");
        fileName = filePath.substring(len + 1);
        String type = filePath.substring(0, len);
        String[] typeArray = type.split("/");
        for (String s : typeArray) {
            if (!checkDirectory(ftp,s)) {
                ftp.mkdir(s);
                ftp.chdir(s);
            }
        }
        ftp.put(inStream, fileName);
        disconnect();
        return filePath;
    }

    /**
     * 删除ftp文件     *     * @param filePath 文件路径     * @throws Exception
     */
    public void deleteFile(String filePath) throws Exception {
        String fileName = "";
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);
            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                if (!checkDirectory(ftp, s)) {
                    throw new Exception("路径错误");
                }
            }
        }
        ftp.delete(fileName);
        disconnect();
    }

    //根据当前文件生成 文件夹
    private  String getTimePath() {
        Date now = new Date();
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd/");
        return format.format(now);
    }
}